﻿package com.jxl.dnd.combat
{
	import flash.events.EventDispatcher;
	
	public class Round extends EventDispatcher
	{
		public var combatant_array:Array;
		public var currentCombatant:Object;
		public var roundCount:Number;
		
		protected var _currentIndex:Number;
		
		
		public function get currentIndex():Number
		{
			return _currentIndex;
		}
		
		public function set currentIndex(val:Number):Void
		{
			_currentIndex = val;
			dispatchEvent({type: "indexChanged", target: this});
		}
		
		public function setCurrentIndex(val:Number):Void
		{
			_currentIndex = val;
		}
		
		public function Round():void
		{
			currentIndex 				= -1;
			roundCount 					= 1;
			combatant_array 			= [];
			combatant_array.removeEventListener("modelChanged", this);
			combatant_array.addEventListener("modelChanged", this);
		}
		
		public function nextCombatant(Void):Void
		{
			if(currentIndex + 1 < combatant_array.length)
			{
				currentIndex++;
			}
			else
			{
				roundCount++;
				dispatchEvent({type: "roundEnd", target: this});
				currentIndex = 0;
			}
			currentCombatant = getCombatantAt(currentIndex);
		}
		
		public function getCombatantIndex(target:Object):Number
		{
			var i = combatant_array.length;
			while(i--)
			{
				var c = combatant_array.getItemAt(i);
				if(c == target)
				{
					return i;
				}
			}
			return -1;
		}
		
		// DataProvider API Functions
		public function addCombatant(target:Object):Void
		{
			combatant_array.addItem(target);
		}
		
		public function addCombatantAt(index:Number, target:Object):Void
		{
			combatant_array.addItemAt(index, target);
		}
		
		public function getCombatantAt(index:Number):Object
		{
			return combatant_array.getItemAt(index);
		}
		
		public function removeAllCombatants(Void):Void
		{
			combatant_array.removeAll();
		}
		
		public function removeCombatantAt(index:Number):Void
		{
			combatant_array.removeItemAt(index);
		}
		
		public function replaceCombatantAt(index:Number, target:Object):Void
		{
			combatant_array.replaceItemAt(index, target);
		}
		
		private function modelChanged(event_obj:Object):Void
		{
			dispatchEvent(event_obj);
		}
		
	}
}